package utils.files;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import play.mvc.Http.Response;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FinalizationException;
import com.google.appengine.api.files.LockException;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

public class GAEFileService {
	
	public static String createFile(String contentType, String fileName, byte[] content)
			throws FileNotFoundException, FinalizationException, LockException, IOException {
		FileService fileService = FileServiceFactory.getFileService();
		// Create a new Blob file with mime-type "text/plain"
		AppEngineFile file = fileService.createNewBlobFile(contentType, fileName);
		// Open a channel to write to it
		boolean lock = true;
		FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
		// Different standard Java ways of writing to the channel
		// are possible. Here we use a PrintWriter:
		writeChannel.write(ByteBuffer.wrap(content));
		// Now finalize
		writeChannel.closeFinally();
		BlobKey key = fileService.getBlobKey(file);
		return key.getKeyString();
	}
	
	public static void deleteFile(String key) {
		BlobKey blobKey = new BlobKey(key);
		BlobstoreServiceFactory.getBlobstoreService().delete(blobKey);
	}
	
}